package logging;

import java.io.*;
import java.util.*;

/**
 * Logging class which writes to the local log.txt file.
 * @author BDS
 */
public class Logger
{
	/**
	 * Static constructor.
	 */
	private Logger() { }

	/**
	 * Getter for the full path of the log.txt file.
	 * @return The full path of the log.txt file.
	 */
	public static String getLogFilePath()
	{
		return System.getProperty("user.dir") + "\\log.txt";
	}

	/**
	 * Writes the Exception to the log file.
	 * @param exception The Exception to be logged.
	 */
	public static void logException(Exception exception)
	{
		logMessage(exception.getClass().getName() + ": " + exception.getMessage());
		for (StackTraceElement stackTraceElement : exception.getStackTrace())
		{
			logMessage("    " + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName() + " Line " + stackTraceElement.getLineNumber());
		}
	}

	/**
	 * Writes the String to the log file.
	 * @param message The String to be logged.
	 */
	public static void logMessage(String message)
	{
		BufferedWriter writer = null;

		try
		{
			if (message != null && !message.equals(""))
			{
				writer = new BufferedWriter(new FileWriter(getLogFilePath(), true));
				writer.write(new Date().toString() + " ");
				writer.write(message);
				writer.write(System.getProperty("line.separator"));
			}
		}
		catch (IOException ಠ_ಠ)
		{
			// Logger exceptions are swallowed.
		}
		finally
		{
			close(writer);
		}
	}

	/**
	 * Helper function for closing Closeable objects.
	 */
	private static void close(Closeable closeable)
	{
		if (closeable == null) return;
		
		try
		{
			closeable.close();
		}
		catch (IOException ಠ_ಠ)
		{
			// Logger exceptions are swallowed.
		}
	}
}
